<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="auto">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="客户名称" prop="customerId">
        <el-select
          v-model="formData.customerId"
          :disabled="formData.customerDefault"
          class="w-1/1"
          filterable
          placeholder="请选择客户"
          @change="handleCustomerChange(formData.customerId)"
        >
          <el-option
            v-for="item in customerList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="运营经理" prop="managerName">
        <el-input readonly v-model="managerName" disabled/>
      </el-form-item>
      <el-form-item label="营业状态" prop="runningStatus">
        <el-input readonly v-model="businessStatus" disabled/>
      </el-form-item>
    </el-form>
    <!-- 子表的表单 -->
    <el-tabs v-model="subTabsName">
      <el-tab-pane label="易制毒、易制爆管理" name="compliancePde">
        <CompliancePdeForm ref="compliancePdeFormRef" :compliance-id="formData.id" />
      </el-tab-pane>
      <el-tab-pane label="剧毒品管理" name="complianceDrugs">
        <ComplianceDrugsForm ref="complianceDrugsFormRef" :compliance-id="formData.id" />
      </el-tab-pane>
      <el-tab-pane label="合规性手续" name="complianceProcedures">
        <ComplianceProceduresForm ref="complianceProceduresFormRef" :compliance-id="formData.id" />
      </el-tab-pane>
      <el-tab-pane label="生产管理员" name="complianceAdmin">
        <ComplianceAdminForm ref="complianceAdminFormRef" :compliance-id="formData.id" />
      </el-tab-pane>
      <el-tab-pane label="主要负责人" name="complianceIncharge">
        <ComplianceInchargeForm ref="complianceInchargeFormRef" :compliance-id="formData.id" />
      </el-tab-pane>
      <el-tab-pane label="特种/危险作业人员信息" name="complianceOperator">
        <ComplianceOperatorForm ref="complianceOperatorFormRef" :compliance-id="formData.id" />
      </el-tab-pane>
      <el-tab-pane label="特种设备信息" name="complianceSpecialEquipment"> 
        <ComplianceSpecialEquipmentForm ref="complianceSpecialEquipmentFormRef" :compliance-id="formData.id" />
      </el-tab-pane>
    </el-tabs>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getDictObj, DICT_TYPE } from '@/utils/dict'
import { ComplianceApi, ComplianceVO } from '@/api/crm/compliance'
import ComplianceDrugsForm from './components/ComplianceDrugsForm.vue'
import CompliancePdeForm from './components/CompliancePdeForm.vue'
import ComplianceProceduresForm from './components/ComplianceProceduresForm.vue'
import ComplianceAdminForm from './components/ComplianceAdminForm.vue'
import ComplianceInchargeForm from './components/ComplianceInchargeForm.vue'
import ComplianceOperatorForm from './components/ComplianceOperatorForm.vue'
import ComplianceSpecialEquipmentForm from './components/ComplianceSpecialEquipmentForm.vue'
import * as CustomerApi from '@/api/crm/customer'
/** CRM 企业合规性安全管理信息 表单 */
defineOptions({ name: 'ComplianceForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const customerList = ref<CustomerApi.CustomerVO[]>([])
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  customerId: undefined as unknown as number,
  customerDefault: false,
})
const formRules = reactive({
  customerId: [{ required: true, message: '客户编号不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const managerName = ref() // 运营经理
const businessStatus = ref() // 营业状态
/** 子表的表单 */
const subTabsName = ref('compliancePde')
const complianceDrugsFormRef = ref()
const compliancePdeFormRef = ref()
const complianceProceduresFormRef = ref()
const complianceAdminFormRef = ref()
const complianceInchargeFormRef = ref()
const complianceOperatorFormRef = ref()
const complianceSpecialEquipmentFormRef = ref()

const handleCustomerChange = async (customerId: number) => {
  if (!customerId) {
    managerName.value = ''
    businessStatus.value = ''
    return
  }
  const customer = customerList.value.find<CustomerApi.CustomerVO>((item) => item.id === customerId)
  managerName.value = customer?.ownerUserName
  const businessStatusObj = getDictObj(DICT_TYPE.CRM_BUSINESS_STATUS, customer?.businessStatus)
  businessStatus.value = businessStatusObj?.label ?? ''
}
/** 打开弹窗 */
const open = async (type: string, id?: number, customerId?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id || customerId) {
    formLoading.value = true
    try {
      if (id) {
        formData.value = await ComplianceApi.getCompliance(id)
        formData.value.customerDefault = true // 默认客户的选择，不允许变
      }else{
        formData.value.customerId = customerId
        formData.value.customerDefault = true // 默认客户的选择，不允许变
      }
      const res = await CustomerApi.getCustomer(customerId ?? formData.value.customerId)
      managerName.value = res.ownerUserName
      businessStatus.value =
        getDictObj(DICT_TYPE.CRM_BUSINESS_STATUS, res.businessStatus)?.label ?? ''
    } finally {
      formLoading.value = false
    }
  }
  // 获得客户列表
  customerList.value = await CustomerApi.getCustomerSimpleList()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 校验子表单
  try {
    await compliancePdeFormRef.value.validate()
    if (compliancePdeFormRef.value.getData().length === 0) {
      message.warning('易制毒、易制爆管理数据不能为空')
      throw {}
    }
  } catch (e) {
    subTabsName.value = 'compliancePde'
    return
  }
  try {
    await complianceDrugsFormRef.value.validate()
    if (complianceDrugsFormRef.value.getData().length === 0) {
      message.warning('剧毒品管理数据不能为空')
      throw {}
    }
  } catch (e) {
    subTabsName.value = 'complianceDrugs'
    return
  }
  try {
    await complianceProceduresFormRef.value.validate()
    if (complianceProceduresFormRef.value.getData().length === 0) {
      message.warning('合规性手续数据不能为空')
      throw {}
    }
  } catch (e) {
    subTabsName.value = 'complianceProcedures'
    return
  }
  try {
    await complianceAdminFormRef.value.validate()
  } catch (e) {
    subTabsName.value = 'complianceAdmin'
    return
  }
  try {
    await complianceInchargeFormRef.value.validate()
  } catch (e) {
    subTabsName.value = 'complianceIncharge'
    return
  }
  try {
    await complianceOperatorFormRef.value.validate()
  } catch (e) {
    subTabsName.value = 'complianceOperator'
    return
  }
  try {
    await complianceSpecialEquipmentFormRef.value.validate()
  } catch (e) {
    subTabsName.value = 'complianceSpecialEquipment'
    return
  }
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as ComplianceVO
    // 拼接子表的数据
    data.compliancePdes = compliancePdeFormRef.value.getData()
    data.complianceDrugss = complianceDrugsFormRef.value.getData()
    data.complianceProceduress = complianceProceduresFormRef.value.getData()
    data.complianceAdmins = complianceAdminFormRef.value.getData()
    data.complianceIncharges = complianceInchargeFormRef.value.getData()
    data.complianceOperators = complianceOperatorFormRef.value.getData()
    data.complianceSpecialEquipments = complianceSpecialEquipmentFormRef.value.getData()
    if (formType.value === 'create') {
      await ComplianceApi.createCompliance(data)
      message.success(t('common.createSuccess'))
    } else {
      await ComplianceApi.updateCompliance(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    customerId: undefined as unknown as number,
    customerDefault: false,
  }
  managerName.value = ''
  businessStatus.value = ''
  formRef.value?.resetFields()
}
</script>
